package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/validator/v10"
	"inspector/internal"
	"inspector/internal/config"
	"inspector/internal/dao/mysql"
	"inspector/internal/utils"
	"inspector/pkg/i18n"
	"inspector/pkg/log"
	"net/http"
	"reflect"
	"strings"
)

var (
	ServiceAddr = fmt.Sprintf("%s:%d", config.Get().GetServerConfig().Address, config.Get().GetServerConfig().Port)
)

func Init() {
	_, err := mysql.InitDB()
	if err != nil {
		fmt.Println(fmt.Sprintf("init db connection error: %v", err))
		return
	}
	logConfig := config.Get().GetLogConfig()
	logOption := &log.Options{
		Name:              logConfig.Name,
		Development:       logConfig.Development,
		Level:             logConfig.Level,
		Format:            logConfig.Format,
		EnableColor:       logConfig.EnableColor,
		DisableCaller:     logConfig.DisableCaller,
		DisableStacktrace: logConfig.DisableStacktrace,
		OutputPaths:       logConfig.OutputPaths,
		ErrorOutputPaths:  logConfig.ErrorOutputPaths,
	}
	log.Init(logOption)
	i18n.Init()
	utils.Init()
}

func main() {
	Init()
	r := gin.New()
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		v.RegisterTagNameFunc(func(fld reflect.StructField) string {
			name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
			if name == "-" {
				return ""
			}
			return name
		})
	}
	internal.InitRouter(r)
	if err := http.ListenAndServe(ServiceAddr, r); err != nil {
		log.Fatalf(err.Error())
	}
}
